import axios from 'axios'
import {router} from './../router.js'
import cookie from './../common/js/cookie_utils.js'

axios.defaults.timeout = 150000;
axios.defaults.withCredentials=true

axios.interceptors.request.use((config) => {
  if(config.method === 'post') {
    let csrftoken = cookie.getCookie('csrftoken')
    console.log('csrftoken')
    console.log(csrftoken)
    config.headers["X-CSRFToken"] = csrftoken
  }
  return config
}, (error) => {
  console.log('request err')
  console.log(error)
  return Promise.reject(error);
});

axios.interceptors.response.use((res) => {
  return res;
}, (error) => {
  console.log('response err')
  console.log(error)
  if(error.response) {
      switch (error.response.status) {
        case 401:
          console.log('401 not authorized')
          console.log(error.response)
            // 返回 401 清除token信息并跳转到登录页面
            sessionStorage.removeItem('user');
            router.replace({
                path: '/login',
                // query: {redirect: router.currentRoute.fullPath}
            })
            break
        case 403:
          console.log('403 denied')
          console.log(error.response)
            // 返回 401 清除token信息并跳转到登录页面
            sessionStorage.removeItem('user');
            router.replace({
                path: '/login',
                // query: {redirect: router.currentRoute.fullPath}
            })
            break

    }
  }
  return Promise.reject(error);
});

export default axios;
